package vashion.azeroth.api.controller.member;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import vashion.azeroth.api.controller.base.BaseController;
import vashion.azeroth.common.common.check.FormatCheck;
import vashion.azeroth.contant.AzerothConstants;
import vashion.azeroth.contant.GenericErrorEnum;
import vashion.azeroth.contant.MemberErrorEnum;
import vashion.azeroth.contant.VerificationCodeErrorEnum;
import vashion.azeroth.core.manager.personal.SMSVerificationCodeManager;
import vashion.azeroth.core.personal.pojo.PersonalInviteCode;
import vashion.azeroth.core.personal.pojo.PersonalMember;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.core.service.PersonalInviteCodeService;
import vashion.azeroth.core.service.PersonalMemberService;

@Controller
@RequestMapping("/member")
public class MemberController extends BaseController {

	@Autowired
	private PersonalMemberService<PersonalMember> memberService;
	@Autowired
	private PersonalInviteCodeService<PersonalInviteCode> inviteCodeService;
	@Autowired
	private SMSVerificationCodeManager verificationCodeManager;

	@Value("#{settings['needInviteCode']}")
	private Boolean needInviteCode;

	/**
	 * 注册接口
	 * 
	 * @param member
	 * @return
	 */
	@RequestMapping("register.htm")
	@ResponseBody
	public ApiResult<PersonalMember> register(@ModelAttribute("member") PersonalMember member,
			@RequestParam(value = "code", required = false) String code) {

		if (StringUtils.isBlank(member.getMemberName())) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
					"用户名" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		// if(!FormatCheck.isMobile(member.getMemberName())) {
		// return
		// ApiResult.newErrorResult(GenericErrorEnum.PARAM_FORMAT_ERROR.getErrorCode(),
		// "用户名" + GenericErrorEnum.PARAM_FORMAT_ERROR.getErrorMessage());}
		//
		if (StringUtils.isBlank(member.getMemberPwd())) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
					"密码" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		if (!FormatCheck.isLegalPassword(member.getMemberPwd())) {
			return ApiResult.newErrorResult(GenericErrorEnum.PARAM_FORMAT_ERROR.getErrorCode(),
					"密码" + GenericErrorEnum.PARAM_FORMAT_ERROR.getErrorMessage());
		}

		if (!needInviteCode) {
			// 如果注册不需要注册码，自动生产一个注册码并使用
			Long supplierId = 1L;
			inviteCodeService.generateInviteCode(supplierId.toString(), 0);
			PersonalInviteCode inviteCodeParam = new PersonalInviteCode();
			inviteCodeParam.setMemberId(supplierId);
			inviteCodeParam.setStatus(AzerothConstants.PersonalInviteCode.PersonalInviteCodeStatus.unused);
			List<PersonalInviteCode> inviteCodeList = inviteCodeService.getAllInviteCode(inviteCodeParam).getData();
			for (PersonalInviteCode inviteCodeTemp : inviteCodeList) {
				if (inviteCodeTemp.getStatus() == AzerothConstants.PersonalInviteCode.PersonalInviteCodeStatus.unused) {
					member.setInviteCode(inviteCodeTemp.getCode());
					break;
				}
			}
		}

		if (StringUtils.isBlank(member.getInviteCode())) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
					"邀请码" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		// if(StringUtils.isBlank(code)) {
		// return
		// ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
		// "验证码" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		// }
		//
		// int checkResult =
		// verificationCodeManager.checkVerificationCode(member.getMemberName(),
		// code,
		// AzerothConstants.VerificationCode.VerificationCodeType.register);
		// //验证码错误
		// if (checkResult == 0) {
		// return
		// ApiResult.newErrorResult(VerificationCodeErrorEnum.CHECK_ERROR.getErrorCode(),
		// VerificationCodeErrorEnum.CHECK_ERROR.getErrorMessage());
		// }
		// //验证码过期
		// if (checkResult == 2) {
		// return
		// ApiResult.newErrorResult(VerificationCodeErrorEnum.EXPIRED.getErrorCode(),
		// VerificationCodeErrorEnum.EXPIRED.getErrorMessage());
		// }

		ApiResult<PersonalMember> result = memberService.register(member);

		return result;
	}

	/**
	 * 登录接口
	 */
	@RequestMapping("login.htm")
	@ResponseBody
	public ApiResult<PersonalMember> login(@ModelAttribute PersonalMember member) {

		if (StringUtils.isBlank(member.getMemberName())) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
					"用户名" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		if (!FormatCheck.isLegalPassword(member.getMemberPwd())) {
			return ApiResult.newErrorResult(GenericErrorEnum.PARAM_FORMAT_ERROR.getErrorCode(),
					"密码" + GenericErrorEnum.PARAM_FORMAT_ERROR.getErrorMessage());
		}

		ApiResult<PersonalMember> result = memberService.login(member);

		return result;
	}

	/**
	 * 自动登录接口
	 * 
	 * @param member
	 * @return
	 */
	@RequestMapping("autoLogin.htm")
	@ResponseBody
	public ApiResult<PersonalMember> autoLogin(@ModelAttribute PersonalMember member) {
		if (null == member.getMemberId()) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
					"memberId" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}
		if (StringUtils.isBlank(member.getToken())) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
					"token" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		ApiResult<PersonalMember> result = memberService.autoLogin(member);

		return result;
	}

	/**
	 * 修改用户信息接口
	 * 
	 * @param member
	 * @return
	 */
	@RequestMapping("modifyMember.htm")
	@ResponseBody
	public ApiResult<PersonalMember> modifyMember(@ModelAttribute PersonalMember member) {
		if (null == member.getMemberId()) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
					"memberId" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		ApiResult<PersonalMember> result = memberService.modifyMember(member);
		return result;
	}

	/**
	 * 查询已邀请的用户
	 * 
	 * @param member
	 * @return
	 */
	@RequestMapping("findInvitedMember.htm")
	@ResponseBody
	public ApiResult<Map<String, Object>> findInvitedMember(@ModelAttribute("member") PersonalMember member) {
		if (null == member.getMemberId()) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
					"inviteMemberId" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}
		PersonalMember invitedMember = new PersonalMember();
		invitedMember.setInviteMemberId(member.getMemberId());
		ApiResult<Map<String, Object>> memberList = (ApiResult<Map<String, Object>>) memberService
				.findInvitedMember(invitedMember);
		return memberList;
	}

	@RequestMapping("checkMember.htm")
	@ResponseBody
	public ApiResult<PersonalMember> checkMember(@ModelAttribute PersonalMember member) {
		ApiResult<PersonalMember> result = new ApiResult<PersonalMember>();
		if (null == member) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
					"参数" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		try {
			result = memberService.checkMember(member);
		} catch (Exception e) {
			return ApiResult.newErrorResult(MemberErrorEnum.INCORRECT.getErrorCode(),
					"参数" + MemberErrorEnum.INCORRECT.getErrorMessage());
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("findPwd.htm")
	@ResponseBody
	public <T> ApiResult<T> findPwd(@RequestParam(value = "newPwd", required = true) String newPwd,
			@RequestParam(value = "memberName", required = true) String memberName,
			@RequestParam(value = "code", required = false) String code) {

		ApiResult<T> result = new ApiResult<T>();

		if (null == memberName || StringUtils.isBlank(String.valueOf(memberName))) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
					"用户名" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		if (StringUtils.isBlank(newPwd)) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
					"新密码" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		// 验证新密码格式
		if (!FormatCheck.isLegalPassword(newPwd)) {
			return ApiResult.newErrorResult(GenericErrorEnum.PARAM_FORMAT_ERROR.getErrorCode(),
					"新密码" + GenericErrorEnum.PARAM_FORMAT_ERROR.getErrorMessage());
		}

		// if(StringUtils.isBlank(code)) {
		// return
		// ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
		// "验证码" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		// }
		//
		// int checkResult =
		// verificationCodeManager.checkVerificationCode(memberName, code,
		// AzerothConstants.VerificationCode.VerificationCodeType.findPwd);
		// //验证码错误
		// if (checkResult == 0) {
		// return
		// ApiResult.newErrorResult(VerificationCodeErrorEnum.CHECK_ERROR.getErrorCode(),
		// VerificationCodeErrorEnum.CHECK_ERROR.getErrorMessage());
		// }
		// //验证码过期
		// if (checkResult == 2) {
		// return
		// ApiResult.newErrorResult(VerificationCodeErrorEnum.EXPIRED.getErrorCode(),
		// VerificationCodeErrorEnum.EXPIRED.getErrorMessage());
		// }

		try {
			result = (ApiResult<T>) memberService.findPwd(newPwd, memberName);
		} catch (Exception e) {
			return ApiResult.newErrorResult(MemberErrorEnum.UPDATE_PWD_FAILED.getErrorCode(),
					MemberErrorEnum.UPDATE_PWD_FAILED.getErrorMessage());
		}

		return result;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("updatePwd.htm")
	@ResponseBody
	public <T> ApiResult<T> updatePwd(String oldPwd, String newPwd, Long memberId) {

		ApiResult<T> result = new ApiResult<T>();

		if (StringUtils.isBlank(oldPwd)) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
					"旧密码" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		if (StringUtils.isBlank(newPwd)) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
					"新密码" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		// 验证新密码格式
		if (!FormatCheck.isLegalPassword(newPwd)) {
			return ApiResult.newErrorResult(GenericErrorEnum.PARAM_FORMAT_ERROR.getErrorCode(),
					"新密码" + GenericErrorEnum.PARAM_FORMAT_ERROR.getErrorMessage());
		}

		if (null == memberId || StringUtils.isBlank(String.valueOf(memberId))) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(),
					"会员ID" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}

		try {
			result = (ApiResult<T>) memberService.updatePwd(oldPwd, newPwd, memberId);
		} catch (Exception e) {
			return ApiResult.newErrorResult(MemberErrorEnum.UPDATE_PWD_FAILED.getErrorCode(),
					MemberErrorEnum.UPDATE_PWD_FAILED.getErrorMessage());
		}
		return result;
	}

	@RequestMapping("handlePayPwd.htm")
	@ResponseBody
	public ApiResult<PersonalMember> handlePayPwd(Long memberId, String type, String newPwd) {

		return memberService.handlePayPwd(memberId, type, newPwd);
	}

	@RequestMapping("checkPayPwd.htm")
	@ResponseBody
	public ApiResult<String> checkPayPwd(Long memberId, String pwd) {

		return memberService.checkPayPwd(memberId, pwd);
	}

	/**
	 * 发送验证码短信
	 * 
	 * @param memberName
	 * @param purpose
	 * @return
	 */
	@RequestMapping("sendVerificationCode.htm")
	@ResponseBody
	public ApiResult<Boolean> sendVerificationCode(
			@RequestParam(value = "memberName", required = true) String memberName,
			@RequestParam(value = "purpose", required = true) int purpose) {
		boolean result = verificationCodeManager.sendSMSVerificationCode(memberName, purpose);
		if (result) {
			return ApiResult.newSuccessResult(result);
		}
		return ApiResult.newErrorResult(VerificationCodeErrorEnum.SEND_ERROR.getErrorCode(),
				VerificationCodeErrorEnum.SEND_ERROR.getErrorMessage());
	}

	/**
	 * 检查验证码
	 * 
	 * @param memberName
	 * @param code
	 * @param purpose
	 * @return
	 */
	@RequestMapping("checkVerificationCode.htm")
	@ResponseBody
	public ApiResult<Boolean> checkVerificationCode(
			@RequestParam(value = "memberName", required = true) String memberName,
			@RequestParam(value = "code", required = true) String code,
			@RequestParam(value = "purpose", required = true) int purpose) {
		int result = verificationCodeManager.checkVerificationCode(memberName, code, purpose);
		if (result == 1) {
			return ApiResult.newSuccessResult(true);
		} else if (result == 2) {
			return ApiResult.newErrorResult(VerificationCodeErrorEnum.EXPIRED.getErrorCode(),
					VerificationCodeErrorEnum.EXPIRED.getErrorMessage());
		}
		return ApiResult.newErrorResult(VerificationCodeErrorEnum.CHECK_ERROR.getErrorCode(),
				VerificationCodeErrorEnum.CHECK_ERROR.getErrorMessage());
	}

	/**
	 * 注册代理商账号，是否需要邀请码
	 * 
	 * @return 注册代理商账号，是否需要邀请码
	 */
	@RequestMapping("needInviteCode.htm")
	@ResponseBody
	public ApiResult<Boolean> needInviteCode() {
		return ApiResult.newSuccessResult(needInviteCode);
	}
}
